package com.xu.a2019;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;

/**
 * @author by yaodao,
 * @date on 2018/10/18.
 * PS: Not easy to write code, please indicate.
 */
public class BaseViewHolder {

    private View convertView;
    private SparseArray<View> views;

    private BaseViewHolder(View convertView) {
        this.views = new SparseArray<>();
        this.convertView = convertView;
        convertView.setTag(this);
    }

    public static BaseViewHolder getInstance(Context context, View convertView, int layout) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(layout, null);
            return new BaseViewHolder(convertView);
        }
        // 重用convertView
        return (BaseViewHolder) convertView.getTag();
    }

    @SuppressWarnings("unchecked")
    public <T extends View> T findViewById(int id) {
        // 同id的控件可重复使用，无需再次findViewById
        View view = views.get(id);
        if (view == null) {
            view = convertView.findViewById(id);
            // 将此id的控件添加进sparseArray
            views.append(id, view);
        }
        return (T) view;
    }

    public View getConvertView() {
        return convertView;
    }

}
